﻿#include "server.h"
#include "ui_server.h"

Server::Server(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Server)
{
    ui->setupUi(this);

    this->setFixedSize(500,700);
    ui->sIP->setText("127.0.0.1");
    ui->sPort->setText("8765");

    // 创建监听套接字
    server = new QTcpServer(this);

    // 监听
    server->listen(QHostAddress(ui->sIP->text()), ui->sPort->text().toInt());

    // 新的链接
    connect(server, &QTcpServer::newConnection, this, [=]()
    {
        conn = server->nextPendingConnection();   // 返回客户端的套接字对象地址
        ui->record->append("had new client connect.....");

        // 接收客户端消息
        connect(conn, &QTcpSocket::readyRead, this, [=]()
        {
            QByteArray array = conn->readAll();
            ui->record->append(array);
        });
    });
}

Server::~Server()
{
    delete ui;
}

void Server::on_sendBtn_clicked()
{
    // 发送数据
    conn->write(ui->msg->toPlainText().toUtf8());
    ui->record->append("Server Say: " + ui->msg->toPlainText());

    // 清楚发送消息框的内容
    ui->msg->clear();
}
